package cn.xiaopengstack.domain.pay.service;

import cn.xiaopengstack.domain.order.model.entity.PayOrderEntity;
import cn.xiaopengstack.domain.order.repository.IOrderRepository;
import cn.xiaopengstack.domain.pay.event.PayResultHandelEvent;
import cn.xiaopengstack.domain.pay.model.entity.PayResultEntity;
import lombok.extern.slf4j.Slf4j;

/**
 * @author jiangyangang
 */
@Slf4j
public abstract class AbsPayService implements IPayService{

    protected IOrderRepository orderRepository;

    public AbsPayService(IOrderRepository orderRepository) {
        this.orderRepository = orderRepository;
    }

    /**
     * 执行支付结果处理逻辑
     * @param payResult
     */
    @Override
    public void executePayResultHandel(Object payResult) throws Exception {
        PayResultEntity payResultEntity = analysisPayResult(payResult);
        changeOrderStatus(payResultEntity);
    }

    /**
     * 解析支付结果
     * @param payResult
     * @return
     */
    protected abstract PayResultEntity analysisPayResult(Object payResult) throws Exception;

    /**
     * 可移到order领域，此处只发MQ即可
     * @param payResultEntity
     */
    protected void changeOrderStatus(PayResultEntity payResultEntity) {
        // 发送通知
        PayResultHandelEvent payResultHandelEvent = new PayResultHandelEvent(
                PayResultHandelEvent.PayResultMessage.builder()
                        .payTime(payResultEntity.getPayTime())
                        .statusEnumVO(payResultEntity.getOrderStatusEnumVO())
                        .userId(payResultEntity.getUserId())
                        .orderId(payResultEntity.getOrderId())
                        .payOrderId(payResultEntity.getPayChannelOrderId())
                        .build(),
                payResultEntity.getOrderId());
        orderRepository.sendOrderPayResultMsg(payResultHandelEvent);
    };
}
